<template>
  <!-- 顶部导航 -->
  <div class="header">
    <div class="nav-links">
      <button @click="handleLogout" class="logout-btn">登出</button>
    </div>
  </div>

  <!-- 主体内容 -->
  <div class="main">
    <!-- 左侧菜单 -->
    <div class="sidebar">
      <div class="logo">
        <img src="@/assets/Logo.png" alt="Logo" />
      </div>
      <div class="system-title">管理系统</div>
      <ul class="menu">
        <li><router-link to="/manager" class="menu-link">首页</router-link></li>

        <li class="parent-menu" @click="toggleMenu('user')">
          <span class="menu-item">
            <span>用户管理</span>
            <span class="toggle-icon">{{ expanded.user ? '∨' : '^' }}</span>
          </span>
          <ul v-show="expanded.user" class="submenu">
            <li><router-link to="/userlist" class="submenu-link">用户列表</router-link></li>
            <li><router-link to="/adminlist" class="submenu-link">管理员列表</router-link></li>
          </ul>
        </li>

        <li class="parent-menu" @click="toggleMenu('product')">
          <span class="menu-item">
            <span>商品管理</span>
            <span class="toggle-icon">{{ expanded.product ? '∨' : '^' }}</span>
          </span>
          <ul v-show="expanded.product" class="submenu">
            <li><router-link to="/productlist" class="submenu-link">商品列表</router-link></li>
          </ul>
        </li>
      </ul>
    </div>

    <!-- 右侧静态内容 -->
    <div class="main-content">
      <div class="dashboard-cards">
        <div class="card uv-card">
          <div class="card-title">
            <span class="card-icon">👥</span>
            访客数
            <span class="update-time">{{ lastUpdateText }}</span>
          </div>
          <div class="card-value">{{ formatNumber(stats.todayUv) }}</div>
          <div class="card-trend" :class="uvTrend.direction">
            {{ uvTrend.text }}
          </div>
        </div>
        <div class="card click-card">
          <div class="card-title">
            <span class="card-icon">🔗</span>
            今日跳转数
            <span class="update-time">{{ lastUpdateText }}</span>
          </div>
          <div class="card-value">{{ formatNumber(stats.todayLinkClicks) }}</div>
          <div class="card-trend" :class="clickTrend.direction">
            {{ clickTrend.text }}
          </div>
        </div>
      </div>

      <div class="chart-section">
      <div class="chart-tabs">
          <div class="chart-tab" :class="{ active: activeTab === '6d' }" @click="switchTab('6d')">
          近六天
        </div>
          <div class="chart-tab" :class="{ active: activeTab === '30d' }" @click="switchTab('30d')">
          近30天
        </div>
          <div class="chart-tab" :class="{ active: activeTab === 'quarter' }" @click="switchTab('quarter')">
          近一季度
        </div>
          <div class="chart-tab" :class="{ active: activeTab === 'year' }" @click="switchTab('year')">
          近一年
        </div>
          <button class="refresh-btn" @click="refreshData" :disabled="loading">
            <span class="refresh-icon" :class="{ spinning: loading }">↻</span>
            刷新数据
          </button>
      </div>

        <div class="charts-container">
          <div class="chart-wrapper">
            <h3 class="chart-title">📈 访客数趋势</h3>
            <div ref="uvChartRef" class="chart-box"></div>
        </div>
          <div class="chart-wrapper">
            <h3 class="chart-title">🔗 链接跳转趋势</h3>
            <div ref="clickChartRef" class="chart-box"></div>
      </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, onUnmounted, computed, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import api from '@/api'

const router = useRouter()
const expanded = reactive({ user: false, product: false })
const activeTab = ref('6d')
const loading = ref(false)

// 统计数据
const stats = ref({
  todayUv: 0,
  todayLinkClicks: 0,
  lastUpdateMinutes: 0,
  dailyStats: []
})

// 图表实例
const uvChartRef = ref(null)
const clickChartRef = ref(null)
let uvChart = null
let clickChart = null

// 计算上次更新文本
const lastUpdateText = computed(() => {
  const minutes = stats.value.lastUpdateMinutes || 0
  if (minutes < 1) return '刚刚更新'
  if (minutes < 60) return `${minutes}分钟前`
  const hours = Math.floor(minutes / 60)
  return `${hours}小时前`
})

// 计算UV趋势
const uvTrend = computed(() => {
  const dailyStats = stats.value.dailyStats || []
  if (dailyStats.length < 2) return { text: '', direction: '' }
  
  const today = dailyStats[dailyStats.length - 1]?.uvCount || 0
  const yesterday = dailyStats[dailyStats.length - 2]?.uvCount || 0
  
  if (yesterday === 0) return { text: '暂无对比数据', direction: 'neutral' }
  
  const change = ((today - yesterday) / yesterday * 100).toFixed(1)
  if (change > 0) return { text: `↑ ${change}%`, direction: 'up' }
  if (change < 0) return { text: `↓ ${Math.abs(change)}%`, direction: 'down' }
  return { text: '持平', direction: 'neutral' }
})

// 计算点击趋势
const clickTrend = computed(() => {
  const dailyStats = stats.value.dailyStats || []
  if (dailyStats.length < 2) return { text: '', direction: '' }
  
  const today = dailyStats[dailyStats.length - 1]?.linkClickCount || 0
  const yesterday = dailyStats[dailyStats.length - 2]?.linkClickCount || 0
  
  if (yesterday === 0) return { text: '暂无对比数据', direction: 'neutral' }
  
  const change = ((today - yesterday) / yesterday * 100).toFixed(1)
  if (change > 0) return { text: `↑ ${change}%`, direction: 'up' }
  if (change < 0) return { text: `↓ ${Math.abs(change)}%`, direction: 'down' }
  return { text: '持平', direction: 'neutral' }
})

// 格式化数字
const formatNumber = (num) => {
  if (num === undefined || num === null) return '0'
  return num.toLocaleString()
}

// 切换标签页
const switchTab = (tab) => {
  activeTab.value = tab
  fetchStats()
}

// 获取统计数据
const fetchStats = async () => {
  loading.value = true
  try {
    const res = await api.getVisitStats({ period: activeTab.value })
    if (res && res.data) {
      stats.value = res.data
    } else if (res) {
      stats.value = res
    }
    await nextTick()
    renderCharts()
  } catch (error) {
    console.error('获取统计数据失败:', error)
    // 使用模拟数据进行展示
    generateMockData()
  } finally {
    loading.value = false
  }
}

// 生成模拟数据（当API不可用时）
const generateMockData = () => {
  const days = activeTab.value === '6d' ? 6 : 
               activeTab.value === '30d' ? 30 : 
               activeTab.value === 'quarter' ? 90 : 365
  
  const dailyStats = []
  const today = new Date()
  
  for (let i = days - 1; i >= 0; i--) {
    const date = new Date(today)
    date.setDate(date.getDate() - i)
    const dateStr = activeTab.value === 'year' 
      ? `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
      : `${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    
    dailyStats.push({
      date: dateStr,
      uvCount: Math.floor(Math.random() * 500) + 100,
      linkClickCount: Math.floor(Math.random() * 300) + 50
    })
  }
  
  stats.value = {
    todayUv: dailyStats[dailyStats.length - 1].uvCount,
    todayLinkClicks: dailyStats[dailyStats.length - 1].linkClickCount,
    lastUpdateMinutes: 5,
    dailyStats
  }
  
  nextTick(() => renderCharts())
}

// 刷新数据
const refreshData = async () => {
  loading.value = true
  try {
    await api.refreshVisitStats()
    await fetchStats()
  } catch (error) {
    console.error('刷新数据失败:', error)
    fetchStats()
  }
}

// 渲染图表
const renderCharts = () => {
  const dailyStats = stats.value.dailyStats || []
  const dates = dailyStats.map(item => item.date)
  const uvData = dailyStats.map(item => item.uvCount || 0)
  const clickData = dailyStats.map(item => item.linkClickCount || 0)

  // UV图表配置
  const uvOption = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#00838f',
      borderWidth: 1,
      textStyle: { color: '#333' },
      formatter: '{b}<br/>访客数: <b>{c}</b>'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLine: { lineStyle: { color: '#ddd' } },
      axisLabel: { 
        color: '#666',
        rotate: dates.length > 15 ? 45 : 0,
        fontSize: dates.length > 30 ? 10 : 12
      }
    },
    yAxis: {
      type: 'value',
      axisLine: { show: false },
      splitLine: { lineStyle: { color: '#f0f0f0', type: 'dashed' } },
      axisLabel: { color: '#666' }
    },
    series: [{
      name: '访客数',
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      lineStyle: {
        color: '#00838f',
        width: 3
      },
      itemStyle: {
        color: '#00838f',
        borderColor: '#fff',
        borderWidth: 2
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(0, 131, 143, 0.4)' },
          { offset: 1, color: 'rgba(0, 131, 143, 0.05)' }
        ])
      },
      data: uvData
    }]
  }

  // 点击图表配置
  const clickOption = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#ff7043',
      borderWidth: 1,
      textStyle: { color: '#333' },
      formatter: '{b}<br/>跳转数: <b>{c}</b>'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLine: { lineStyle: { color: '#ddd' } },
      axisLabel: { 
        color: '#666',
        rotate: dates.length > 15 ? 45 : 0,
        fontSize: dates.length > 30 ? 10 : 12
      }
    },
    yAxis: {
      type: 'value',
      axisLine: { show: false },
      splitLine: { lineStyle: { color: '#f0f0f0', type: 'dashed' } },
      axisLabel: { color: '#666' }
    },
    series: [{
      name: '跳转数',
      type: 'bar',
      barWidth: '60%',
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#ff7043' },
          { offset: 1, color: '#ffab91' }
        ]),
        borderRadius: [4, 4, 0, 0]
      },
      emphasis: {
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#ff5722' },
            { offset: 1, color: '#ff7043' }
          ])
        }
      },
      data: clickData
    }]
  }

  // 初始化或更新UV图表
  if (uvChartRef.value) {
    if (!uvChart) {
      uvChart = echarts.init(uvChartRef.value)
    }
    uvChart.setOption(uvOption)
  }

  // 初始化或更新点击图表
  if (clickChartRef.value) {
    if (!clickChart) {
      clickChart = echarts.init(clickChartRef.value)
    }
    clickChart.setOption(clickOption)
  }
}

// 窗口大小变化时重绘图表
const handleResize = () => {
  uvChart?.resize()
  clickChart?.resize()
}

const toggleMenu = (key) => {
  expanded[key] = !expanded[key]
}

const handleLogout = () => {
  router.push('/admin-login')
}

onMounted(() => {
  fetchStats()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  uvChart?.dispose()
  clickChart?.dispose()
})
</script>

<style scoped>
/* ========== 布局基础 ========== */
@import '@/CSS/ManagerPublicCss.css';

/* ========== 右侧内容 ========== */
.main-content {
  width: 85%;
  margin-left: 220px;
  padding: 30px;
  box-sizing: border-box;
  background: #f8f9fa;
  min-height: 100vh;
}

/* ========== 统计卡片 ========== */
.dashboard-cards {
  display: flex;
  gap: 30px;
  margin-bottom: 30px;
}

.card {
  flex: 1;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  padding: 24px;
  min-height: 140px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 40px rgba(102, 126, 234, 0.4);
}

.card.uv-card {
  background: linear-gradient(135deg, #00838f 0%, #00acc1 100%);
  box-shadow: 0 10px 30px rgba(0, 131, 143, 0.3);
}

.card.uv-card:hover {
  box-shadow: 0 15px 40px rgba(0, 131, 143, 0.4);
}

.card.click-card {
  background: linear-gradient(135deg, #ff7043 0%, #ff9800 100%);
  box-shadow: 0 10px 30px rgba(255, 112, 67, 0.3);
}

.card.click-card:hover {
  box-shadow: 0 15px 40px rgba(255, 112, 67, 0.4);
}

.card-title {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9);
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-icon {
  font-size: 18px;
}

.update-time {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
  margin-left: auto;
}

.card-value {
  font-size: 42px;
  font-weight: 700;
  color: #ffffff;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.card-trend {
  font-size: 13px;
  font-weight: 500;
}

.card-trend.up {
  color: #a5d6a7;
}

.card-trend.down {
  color: #ffcdd2;
}

.card-trend.neutral {
  color: rgba(255, 255, 255, 0.7);
}

/* ========== 图表区域 ========== */
.chart-section {
  background: #ffffff;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.chart-tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
  align-items: center;
}

.chart-tab {
  padding: 10px 20px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  color: #666;
  border-radius: 8px;
  transition: all 0.3s ease;
  background: #f5f5f5;
}

.chart-tab:hover {
  background: #e8f5f6;
  color: #00838f;
}

.chart-tab.active {
  background: #00838f;
  color: #ffffff;
  box-shadow: 0 4px 12px rgba(0, 131, 143, 0.3);
}

.refresh-btn {
  margin-left: auto;
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.3s ease;
}

.refresh-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.refresh-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.refresh-icon {
  display: inline-block;
  transition: transform 0.3s ease;
}

.refresh-icon.spinning {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.charts-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24px;
}

.chart-wrapper {
  background: #fafafa;
  border-radius: 12px;
  padding: 20px;
  border: 1px solid #eee;
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
  padding-left: 4px;
}

.chart-box {
  height: 320px;
  width: 100%;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .charts-container {
    grid-template-columns: 1fr;
  }
  
  .dashboard-cards {
    flex-direction: column;
  }
}
</style>
